package me.zhengjie.nettydemo.nettty;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.pojo.entity.Lift;
import me.zhengjie.nettydemo.mapper.LiftNettyMapper;
import me.zhengjie.sqlservilce.LiftSqlService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author : huang
 * @since : 2024/5/9 9:16
 */

@Slf4j
@Component
@Data
public class LiftCenter {

    private static final Logger liftLog = LoggerFactory.getLogger("lift");
    private final LiftNettyMapper liftMapper;
    public static final Map<String, LiftClient> liftClientMap = new ConcurrentHashMap<>();
    private final Thread cronWorker = new Thread(cron(), "电梯心跳工作员");
    private final LiftSqlService liftSqlService;

    public LiftCenter(LiftNettyMapper liftMapper, LiftSqlService liftSqlService) {
        this.liftMapper = liftMapper;
        this.liftSqlService = liftSqlService;
        List<Lift> liftList = liftMapper.selectAll();
        for (Lift lift : liftList) {
            liftLog.info("开始连接");
            LiftClient client = new LiftClient(lift.getIp(), lift.getPort(), lift.getLiftCode(), liftMapper,liftSqlService);
            client.connect();
            this.liftClientMap.put(lift.getLiftCode(), client);
            liftLog.info("连接成功打印map：{}",liftClientMap);
        }
//        this.cronWorker.setDaemon(true);
        this.cronWorker.start();
    }

    @EventListener(classes = {ContextClosedEvent.class})
    public void stop() {
        this.cronWorker.interrupt();
    }

    private Runnable cron() {
        return () -> {
//           while (true) {
//               try {
//                   TimeUnit.SECONDS.sleep(1);
//                   int size = this.liftClientMap.size();
//                   if (size !=0){
//                       for (LiftClient client : this.liftClientMap.values()) {
////                   client.liftInfoHeartbeat();
//                           if (client.getChannel() != null) {
//                               client.liftInfoHeartbeat();
//                           } else {
//                               liftLog.warn("电梯 {} 的通道为 null，跳过心跳检测", client.getLiftCode());
//                           }
//                       }
//                   }
//               } catch (Exception e) {
//                   liftLog.info("电梯心跳工作员退出:{}",e);
////                   break;
//               }
//
//// TODO 做一個判空
//           }

//            for (LiftClient client : this.liftClientMap.values()) {
//                client.disconnect();
//            }
        };
    }

    //呼叫电梯
    public boolean callLift(String liftCode, int startFloor) {
        LiftClient client = this.liftClientMap.get(liftCode);

        if (client == null)
            return false;

        Integer res = client.callLift(startFloor).join();
        return res == 0;
    }

    //关门至某处
    public boolean closeDoorAndGoToFloor(String liftCode, int TargetFloor) {
       LiftClient client = this.liftClientMap.get(liftCode);

        if (client == null)
            return false;

        Integer res = client.closeDoorAndGoToFloor(TargetFloor).join();
        return res == 0;
    }

    //前门关门
    public boolean closeDoor(String liftCode) {
        LiftClient client = this.liftClientMap.get(liftCode);

        if (client == null)
            return false;

        Integer res = client.closeDoor().join();
        return res == 0;
    }

    //前门开门
    public boolean openDoor(String liftCode) {
        LiftClient client = this.liftClientMap.get(liftCode);

        if (client == null)
            return false;

        Integer res = client.openDoor().join();
        return res == 0;
    }

    //控制电梯执行进入AGV模式
    public void maintainAGVMode(String liftCode) {
        LiftClient client = this.liftClientMap.get(liftCode);

        if (client == null){
            client.maintainAGVMode();
        }

    }

    //查询继电器输入
    public boolean liftStatusFrame(String liftCode) {
        LiftClient client = this.liftClientMap.get(liftCode);

        if (client == null)
            return false;

        Integer res = client.liftStatusFrame().join();
        return res == 0;
    }

    //查询继电器输出
    public boolean liftStatusOutput(String liftCode) {
        LiftClient client = this.liftClientMap.get(liftCode);

        if (client == null)
            return false;

        Integer res = client.liftStatusOutput().join();
        return res == 0;
    }

    //控制继电器开启agv专用模式
    public boolean controlLiftStatusOutputOpenIt(String liftCode) {
        LiftClient client = this.liftClientMap.get(liftCode);

        if (client == null)
            return false;

        Integer res = client.controlLiftStatusOutputOpenIt().join();
        return res == 0;
    }

    //控制继电器开启手动模式
    public boolean controlLiftStatusOutputShutDown(String liftCode) {
        LiftClient client = this.liftClientMap.get(liftCode);

        if (client == null)
            return false;

        Integer res = client.controlLiftStatusOutputShutDown().join();
        return res == 0;
    }
}
